package me.zhengjie.service.impl;

import me.zhengjie.domain.WxpayConfig;
import me.zhengjie.repository.WxpayRepository;
import me.zhengjie.service.WxpayService;
import me.zhengjie.service.dto.WxpayDTO;
import me.zhengjie.service.dto.WxpayQueryCriteria;
import me.zhengjie.service.mapper.WxpayMapper;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@CacheConfig(cacheNames = "wxpay")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class WxpayServiceImpl implements WxpayService {

    private final WxpayRepository wxpayRepository;
    private final WxpayMapper wxpayMapper;

    public WxpayServiceImpl(WxpayRepository wxpayRepository, WxpayMapper wxpayMapper) {
        this.wxpayRepository = wxpayRepository;
        this.wxpayMapper = wxpayMapper;
    }

    @Override
    public WxpayConfig find() {
        return null;
    }

    @Override
    public Map<String, Object> queryAll(WxpayQueryCriteria criteria, Pageable pageable) {
        Page<WxpayConfig> page = wxpayRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);

        List<WxpayDTO> list = wxpayMapper.toDto(wxpayRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
        return PageUtil.toPage(list,page.getTotalElements());
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public WxpayDTO create(WxpayConfig resources) {
        return wxpayMapper.toDto(wxpayRepository.save(resources));
    }

}
